<?php
/**
 * 订单
 * @date    2020-01-01
 * @author  kiro
 * @email   294843009@qq.com
 * @version 1.0
 */
namespace App\Http\Controllers\Api\V1;

use App\Models\Config;
use App\Models\Gift;
use App\Models\Give;
use App\Models\Goods;
use App\Models\Order;
use App\Models\UserGiftLog;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends ApiController
{
    // 列表
    public function list(Request $request)
    {
        $page = (int)$request->get('page', 1);
        $limit = (int)$request->get('limit', 10);
        $offset = ($page - 1) * $limit;
        $total = Order::where('user_id', $this->getUserId())
            ->where(function ($query) use ($request) {
                $request->status != '' AND $query->where('status', $request->status);
            })->count();
        $data = Order::where('user_id', $this->getUserId())
            ->where(function ($query) use ($request) {
                $request->status != '' AND $query->where('status', $request->status);
            })
            ->offset($offset)
            ->limit($limit)
            ->orderBy('id', 'DESC')
            ->get();
        foreach ($data as &$value) {
            $goods = Goods::where('id', $value->goods_id)->first();
            $goods->goods_name = htmlspecialchars_decode($goods->goods_name);
            $goods->thumb = dealUrl($goods->thumb);
            $value->goodsInfo = $goods;
            $value->pay_type_str = Order::$type_arr[$value->pay_type] ?? '';
            $value->status_str = Order::$status_arr[$value->status] ?? '';
        }
        return $this->success('成功', [
            'total' => $total,
            'total_page' => ceil($total / $limit),
            'current_page' => $page,
            'list' => $data
        ]);
    }

    /**
     * 下单
     * @param Request $request
     */
    public function do(Request $request)
    {
        $goods_id = $request->get('goods_id', 0);
        $remark = $request->get('remark', '');
        if (empty($this->getUserId())) {
                return $this->error('请先登录');
        }
        if (empty($goods_id)) {
            return $this->error('商品ID不能为空');
        }

        $goods = Goods::where('status', 1)->where('id', $goods_id)->first();

        if (empty($goods)) {
            return $this->error('商品不存在');
        }

        if ($goods->price <= 0) {
            return $this->error('商品金额有问题');
        }

        DB::beginTransaction();
        try {

            $res = Order::add($this->getUserId(), $goods_id, $goods->price, $remark);
            if (!$res) {
                DB::rollBack();
                return $this->error('下单失败');
            }
           DB::commit();
            return $this->success('下单成功', $res);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 余额支付
     * @param Request $request
     */
    public function pay(Request $request)
    {
        $order_id = $request->get('order_id', 0);
        $pay_type = $request->get('pay_type') ?:'AMOUNT';
        if (empty($this->getUserId())) {
            return $this->error('请先登录');
        }
        if (empty($order_id)) {
            return $this->error('订单ID不能为空');
        }

        if (!in_array($pay_type, array_keys(Order::$type_arr))) {
            return $this->error('支付方式不存在');
        }

        $order = Order::whereIn('status', [1, 2])->where('id', $order_id)->first();

        if (empty($order)) {
            return $this->error('订单不存在');
        }

        if ($order->status == 2) {
            return $this->error('订单已支付');
        }

        DB::beginTransaction();
        try {

            $res = Order::setStatus($order_id, 2, $pay_type);
            if (!$res) {
                DB::rollBack();
                return $this->error('支付失败');
            }
            UserService::doAccount($this->getUserId(), -$order->price, '购物扣款', $pay_type, 'BUY_GOODS');
            DB::commit();
            return $this->success('支付成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 取消订单
     * @param Request $request
     */
    public function cancel(Request $request)
    {
        $order_id = $request->get('order_id', 0);
        if (empty($this->getUserId())) {
            return $this->error('请先登录');
        }
        if (empty($order_id)) {
            return $this->error('订单ID不能为空');
        }

        $order = Order::whereIn('status', [1])->where('id', $order_id)->first();

        if (empty($order)) {
            return $this->error('订单不存在或者不能取消');
        }

        DB::beginTransaction();
        try {

            $res = Order::setStatus($order_id, 0);
            if (!$res) {
                DB::rollBack();
                return $this->error('取消失败');
            }
            DB::commit();
            return $this->success('取消成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 取消订单
     * @param Request $request
     */
    public function back(Request $request)
    {
        $order_id = $request->get('order_id', 0);
        if (empty($this->getUserId())) {
            return $this->error('请先登录');
        }
        if (empty($order_id)) {
            return $this->error('订单ID不能为空');
        }

        $order = Order::whereIn('status', [2])->where('id', $order_id)->first();

        if (empty($order)) {
            return $this->error('订单不存在或者不能退回');
        }

        DB::beginTransaction();
        try {

            $res = Order::setStatus($order_id, 3);
            if (!$res) {
                DB::rollBack();
                return $this->error('退回失败');
            }
            DB::commit();
            return $this->success('退回成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }
}
